//
//  NSArray+MKUI.m
//  MKUI
//
//  Created by 苏尚进 on 2022/5/9.
//  Copyright © 2022 moon. All rights reserved.
//

#import "NSArray+MKUI.h"

@implementation NSArray (MKUI)
- (NSArray *)mk_removeObjectsInArray:(NSArray *)otherArray{
    NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:self.count];
    for (id obj in self) {
        if(![otherArray containsObject:obj]){
            [result addObject:obj];
        }
    }
    return result;
}
- (NSArray *)mk_map:(NS_NOESCAPE id _Nullable(^ _Nullable)(id obj))block{
    if(!block){
        return @[];
    }
    return [self mk_mapWithIndex:^id _Nullable(id  _Nonnull obj,NSInteger index) {
        if(block){
            return block(obj);
        }else{
            return nil;
        }
    }];
}
- (NSArray *)mk_mapWithIndex:(NS_NOESCAPE id _Nullable(^ _Nullable)(id obj,NSInteger index))block{
    if(!block){
        return @[];
    }
    NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:self.count];
    for (int i=0;i<self.count;i++) {
        id obj = self[i];
        id newObj = block(obj,i);
        if(newObj){
            [result addObject:newObj];
        }
    }
    return result;
}
- (NSDictionary *)mk_mapDictionary:(NS_NOESCAPE NSDictionary * _Nullable(^ _Nullable)(id obj))block{
    if(!block){
        return @{};
    }
    return [self mk_mapDictionaryWithIndex:^NSDictionary * _Nullable(id  _Nonnull obj,NSInteger index) {
        if(block){
            return block(obj);
        }else{
            return nil;
        }
    }];
}
- (NSDictionary *)mk_mapDictionaryWithIndex:(NS_NOESCAPE NSDictionary * _Nullable(^ _Nullable)(id obj,NSInteger index))block{
    if(!block){
        return @{};
    }
    NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithCapacity:self.count];
    for (int i=0;i<self.count;i++) {
        id obj = self[i];
        NSDictionary *dict = block(obj,i);
        if(dict){
            [result addEntriesFromDictionary:dict];
        }
    }
    return result;
}
- (nullable id)mk_reduce:(NS_NOESCAPE id _Nullable(^ _Nullable)(NSInteger index,id obj,id _Nullable result,BOOL *stop))block first:(nullable id)first{
    id result = first;
    __block BOOL stop = NO;
    if(block){
        for (int i=0; i<self.count; i++) {
            id obj = self[i];
            block(i,obj,result,&stop);
            if(stop){
                break;
            }
        }
    }
    return result;
}
@end

@implementation NSMutableArray (MKUI)
- (void)mk_insertObjects:(NSArray *)objects afterIndex:(NSInteger)index{
    if(objects.count==0)return;
    NSMutableIndexSet *indexset = [[NSMutableIndexSet alloc] init];
    for (int i=0;i<objects.count;i++) {
        [indexset addIndex:index+1+i];
    }
    [self insertObjects:objects atIndexes:indexset];
}
- (void)mk_insertObjectsToTop:(NSArray *)objects{
    [self mk_insertObjects:objects afterIndex:-1];
}
@end
